package com.aps.server.controller;

import com.aps.server.entity.BasicEquipMaintenance;
import com.aps.server.service.BasicEquipMaintenanceService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 设备维护记录控制器
 * 提供设备维护记录相关的REST API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/basic-equip-maintenances")
@RequiredArgsConstructor
@Tag(name = "设备维护记录管理", description = "设备维护记录相关的API接口")
public class BasicEquipMaintenanceController {
    @Resource
     BasicEquipMaintenanceService basicEquipMaintenanceService;
    
    /**
     * 创建设备维护记录
     */
    @PostMapping
    @Operation(summary = "创建设备维护记录", description = "创建一个新的设备维护记录")
    public ResponseEntity<Map<String, Object>> createEquipMaintenance(@RequestBody BasicEquipMaintenance basicEquipMaintenance) {
        try {
            boolean success = basicEquipMaintenanceService.createEquipMaintenance(basicEquipMaintenance);
            if (success) {
                return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "设备维护记录创建成功",
                    "maintenanceId", basicEquipMaintenance.getId()
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "设备维护记录创建失败"
                ));
            }
        } catch (Exception e) {
            log.error("创建设备维护记录失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "创建设备维护记录失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 根据ID查询设备维护记录
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询设备维护记录", description = "根据维护记录ID查询设备维护记录信息（使用配置的租户ID）")
    public ResponseEntity<BasicEquipMaintenance> getEquipMaintenanceById(
            @Parameter(description = "维护记录ID") @PathVariable("id") String id) {
        try {
            BasicEquipMaintenance maintenance = basicEquipMaintenanceService.getEquipMaintenanceById(id);
            if (maintenance != null) {
                return ResponseEntity.ok(maintenance);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("查询设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据ID和租户ID查询设备维护记录
     */
    @GetMapping("/{id}/tenant")
    @Operation(summary = "根据ID和租户ID查询设备维护记录", description = "根据维护记录ID和指定租户ID查询设备维护记录信息")
    public ResponseEntity<BasicEquipMaintenance> getEquipMaintenanceByIdWithTenant(
            @Parameter(description = "维护记录ID") @PathVariable String id,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        try {
            BasicEquipMaintenance maintenance = basicEquipMaintenanceService.getEquipMaintenanceById(id, tenantId);
            if (maintenance != null) {
                return ResponseEntity.ok(maintenance);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("查询设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 更新设备维护记录信息
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新设备维护记录信息", description = "根据维护记录ID更新设备维护记录信息")
    public ResponseEntity<Map<String, Object>> updateEquipMaintenance(
            @Parameter(description = "维护记录ID") @PathVariable String id,
            @RequestBody BasicEquipMaintenance basicEquipMaintenance) {
        try {
            basicEquipMaintenance.setId(id);
            boolean success = basicEquipMaintenanceService.updateEquipMaintenance(basicEquipMaintenance);
            if (success) {
                return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "设备维护记录更新成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "设备维护记录更新失败"
                ));
            }
        } catch (Exception e) {
            log.error("更新设备维护记录失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "更新设备维护记录失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 删除设备维护记录
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除设备维护记录", description = "根据维护记录ID删除设备维护记录（使用配置的租户ID）")
    public ResponseEntity<Map<String, Object>> deleteEquipMaintenance(
            @Parameter(description = "维护记录ID") @PathVariable("id") String id) {
        try {
            boolean success = basicEquipMaintenanceService.deleteEquipMaintenance(id);
            if (success) {
                return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "设备维护记录删除成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "设备维护记录删除失败"
                ));
            }
        } catch (Exception e) {
            log.error("删除设备维护记录失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "删除设备维护记录失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 根据ID和租户ID删除设备维护记录
     */
    @DeleteMapping("/{id}/tenant")
    @Operation(summary = "根据ID和租户ID删除设备维护记录", description = "根据维护记录ID和指定租户ID删除设备维护记录")
    public ResponseEntity<Map<String, Object>> deleteEquipMaintenanceWithTenant(
            @Parameter(description = "维护记录ID") @PathVariable String id,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        try {
            boolean success = basicEquipMaintenanceService.deleteEquipMaintenance(id, tenantId);
            if (success) {
                return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "设备维护记录删除成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "设备维护记录删除失败"
                ));
            }
        } catch (Exception e) {
            log.error("删除设备维护记录失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "删除设备维护记录失败: " + e.getMessage()
            ));
        }
    }
    
    /**
     * 查询当前租户的设备维护记录列表
     */
    @GetMapping("/current-tenant")
    @Operation(summary = "查询当前租户的设备维护记录列表", description = "根据配置的租户ID查询所有设备维护记录")
    public ResponseEntity<List<BasicEquipMaintenance>> getEquipMaintenancesByCurrentTenant() {
        try {
            List<BasicEquipMaintenance> maintenances = basicEquipMaintenanceService.getEquipMaintenancesByTenantId();
            return ResponseEntity.ok(maintenances);
        } catch (Exception e) {
            log.error("根据当前租户ID查询设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据租户ID查询设备维护记录列表
     */
    @GetMapping("/tenant/{tenantId}")
    @Operation(summary = "根据租户ID查询设备维护记录列表", description = "根据指定租户ID查询所有设备维护记录")
    public ResponseEntity<List<BasicEquipMaintenance>> getEquipMaintenancesByTenantId(
            @Parameter(description = "租户ID") @PathVariable("tenantId") String tenantId) {
        try {
            List<BasicEquipMaintenance> maintenances = basicEquipMaintenanceService.getEquipMaintenancesByTenantId(tenantId);
            return ResponseEntity.ok(maintenances);
        } catch (Exception e) {
            log.error("根据租户ID查询设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 分页查询当前租户的设备维护记录列表
     */
    @GetMapping("/current-tenant/page")
    @Operation(summary = "分页查询当前租户的设备维护记录列表", description = "根据配置的租户ID分页查询设备维护记录列表")
    public ResponseEntity<IPage<BasicEquipMaintenance>> getEquipMaintenancesByCurrentTenantPage(
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") int current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        try {
            IPage<BasicEquipMaintenance> page = basicEquipMaintenanceService.getEquipMaintenancesByTenantIdPage(current, size);
            return ResponseEntity.ok(page);
        } catch (Exception e) {
            log.error("分页查询当前租户设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据租户ID分页查询设备维护记录列表
     */
    @GetMapping("/tenant/{tenantId}/page")
    @Operation(summary = "分页查询设备维护记录列表", description = "根据指定租户ID分页查询设备维护记录列表")
    public ResponseEntity<IPage<BasicEquipMaintenance>> getEquipMaintenancesByTenantIdPage(
            @Parameter(description = "租户ID") @PathVariable String tenantId,
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") int current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        try {
            IPage<BasicEquipMaintenance> page = basicEquipMaintenanceService.getEquipMaintenancesByTenantIdPage(current, size, tenantId);
            return ResponseEntity.ok(page);
        } catch (Exception e) {
            log.error("分页查询设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据设备编码查询设备维护记录列表
     */
    @GetMapping("/equip/{equipId}")
    @Operation(summary = "根据设备编码查询设备维护记录列表", description = "根据设备编码和租户ID查询设备维护记录列表")
    public ResponseEntity<List<BasicEquipMaintenance>> getEquipMaintenancesByEquipId(
            @Parameter(description = "设备编码") @PathVariable String equipId,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        try {
            List<BasicEquipMaintenance> maintenances = basicEquipMaintenanceService.getEquipMaintenancesByEquipId(equipId, tenantId);
            return ResponseEntity.ok(maintenances);
        } catch (Exception e) {
            log.error("根据设备编码查询设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据设备编码分页查询设备维护记录列表
     */
    @GetMapping("/equip/{equipId}/page")
    @Operation(summary = "根据设备编码分页查询设备维护记录列表", description = "根据设备编码和租户ID分页查询设备维护记录列表")
    public ResponseEntity<IPage<BasicEquipMaintenance>> getEquipMaintenancesByEquipIdPage(
            @Parameter(description = "设备编码") @PathVariable String equipId,
            @Parameter(description = "租户ID") @RequestParam String tenantId,
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") int current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size) {
        try {
            IPage<BasicEquipMaintenance> page = basicEquipMaintenanceService.getEquipMaintenancesByEquipIdPage(current, size, equipId, tenantId);
            return ResponseEntity.ok(page);
        } catch (Exception e) {
            log.error("根据设备编码分页查询设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 查询正在维护的设备记录
     */
    @GetMapping("/active")
    @Operation(summary = "查询正在维护的设备记录", description = "查询指定租户下正在维护的设备记录")
    public ResponseEntity<List<BasicEquipMaintenance>> getActiveMaintenances(
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        try {
            List<BasicEquipMaintenance> maintenances = basicEquipMaintenanceService.getActiveMaintenances(tenantId);
            return ResponseEntity.ok(maintenances);
        } catch (Exception e) {
            log.error("查询正在维护的设备记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据维护时间范围查询设备维护记录列表
     */
    @GetMapping("/time-range")
    @Operation(summary = "根据维护时间范围查询设备维护记录列表", description = "根据维护时间范围和租户ID查询设备维护记录列表")
    public ResponseEntity<List<BasicEquipMaintenance>> getEquipMaintenancesByTimeRange(
            @Parameter(description = "开始时间") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        try {
            List<BasicEquipMaintenance> maintenances = basicEquipMaintenanceService.getEquipMaintenancesByTimeRange(startTime, endTime, tenantId);
            return ResponseEntity.ok(maintenances);
        } catch (Exception e) {
            log.error("根据维护时间范围查询设备维护记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 统计租户下的设备维护记录数量
     */
    @GetMapping("/count/tenant/{tenantId}")
    @Operation(summary = "统计租户设备维护记录数量", description = "统计指定租户下的设备维护记录数量")
    public ResponseEntity<Long> countEquipMaintenancesByTenantId(
            @Parameter(description = "租户ID") @PathVariable("tenantId") String tenantId) {
        try {
            Long count = basicEquipMaintenanceService.countEquipMaintenancesByTenantId(tenantId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            log.error("统计租户设备维护记录数量失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 统计设备编码下的维护记录数量
     */
    @GetMapping("/count/equip/{equipId}")
    @Operation(summary = "统计设备维护记录数量", description = "统计指定设备编码下的维护记录数量")
    public ResponseEntity<Long> countEquipMaintenancesByEquipId(
            @Parameter(description = "设备编码") @PathVariable String equipId,
            @Parameter(description = "租户ID") @RequestParam String tenantId) {
        try {
            Long count = basicEquipMaintenanceService.countEquipMaintenancesByEquipId(equipId, tenantId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            log.error("统计设备维护记录数量失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 批量创建设备维护记录
     */
    @PostMapping("/batch")
    @Operation(summary = "批量创建设备维护记录", description = "批量创建多个设备维护记录")
    public ResponseEntity<Map<String, Object>> batchCreateEquipMaintenances(@RequestBody List<BasicEquipMaintenance> maintenances) {
        try {
            int successCount = basicEquipMaintenanceService.batchCreateEquipMaintenances(maintenances);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "批量创建设备维护记录完成",
                "totalCount", maintenances.size(),
                "successCount", successCount,
                "failureCount", maintenances.size() - successCount
            ));
        } catch (Exception e) {
            log.error("批量创建设备维护记录失败", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "批量创建设备维护记录失败: " + e.getMessage()
            ));
        }
    }
}
